import time
from fastapi import Request, HTTPException
from fastapi.responses import JSONResponse
from pydantic import ValidationError  # 新增导入Pydantic验证错误类
from app.schemas.error import RestfulErrorResponse  # 新增导入错误响应模型
from app.core.local_logging import setup_logging

logger = setup_logging()


# 全局异常处理中间件
async def global_exception_handler(request: Request, call_next):
    try:
        # 记录请求开始时间
        start_time = time.time()

        # 调用下一个中间件或路由处理函数
        response = await call_next(request)

        # 计算请求处理时间
        process_time = time.time() - start_time
        logger.info(f"[全局异常处理] [请求处理耗时] in {process_time} seconds")

        # 添加处理时间到响应头
        response.headers["X-Process-Time"] = str(process_time)

        # 统一返回格式
        if isinstance(response, JSONResponse):
            data = response.body.decode()
            return JSONResponse(content={
                "code": response.status_code,
                "message": "success",
                "data": data
            },
                headers=response.headers
            )

        return response

    except HTTPException as e:
        # 仅保留 message 字段
        headers = {"Access-Control-Allow-Origin": request.headers.get("Origin")}
        return JSONResponse(
            content={
                "code": e.status_code,
                "message": e.detail,
                "data": None
            },
            headers=headers
        )
    except Exception as e:
        # 仅保留 message 字段
        return JSONResponse(content={
            "code": 500,
            "message": str(e),  # 核心 msg 部分
            "data": None
        },
            headers={"Access-Control-Allow-Origin": request.headers.get("Origin")})


# 处理Pydantic验证错误（422状态码）
async def validation_exception_handler(request: Request, exc: ValidationError):
    # 提取第一个错误的详细信息
    first_error = exc.errors()[0]
    return JSONResponse(
        status_code=422,
        content=RestfulErrorResponse(
            code=422,
            message=first_error["msg"],
            data={"detail": [first_error]}
        ).model_dump()
    )


# 处理业务逻辑抛出的HTTPException
async def http_exception_handler(request: Request, exc: HTTPException):
    # 兼容原始detail格式（字符串或列表）
    message = exc.detail if isinstance(exc.detail, str) else exc.detail[0]["msg"] if exc.detail else "未知错误"
    return JSONResponse(
        status_code=exc.status_code,
        content=RestfulErrorResponse(
            code=exc.status_code,
            message=message,
            data={"detail": exc.detail} if exc.detail else None
        ).model_dump()
    )
